package com.nsgf.library.ui.page.manager;

import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED;
import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_HIDDEN;
import static com.nsgf.library.ui.page.manager.ManagerWorkOrderDetailsActivity.LOCAL_WORK_ORDER_DETAIL;
import static com.nsgf.library.ui.page.manager.ManagerWorkOrderDetailsActivity.LOCAL_WORK_ORDER_FORM;
import static com.nsgf.library.ui.page.manager.WorkOrderMapActivity.getJsonObject;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Parcelable;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.widget.NestedScrollView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.gson.Gson;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.databinding.ActivityNsgfManagerWorkOrderDamDetailsBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.event.RxBus;
import com.nsgf.library.service.LocationService;
import com.nsgf.library.ui.adapter.ManagerDamListAdapter;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.BaseAlterDialog;
import com.nsgf.skjz.utils.Kits;
import com.nsgf.skjz.utils.SPUtil;
import com.nsgf.skjz.utils.SpKey;
import com.nsgf.skjz.utils.StringUtil;
import com.nsgf.skjz.utils.ToastUtils;
import com.nsgf.skjz.utils.Utils;
//import com.tbruyelle.rxpermissions3.RxPermissions;
import com.nsgf.library.photopicker.utils.PermissionsUtils;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import io.reactivex.rxjava3.functions.Consumer;


/**
 * 巡查
 */
public class ManagerWorkOrderDamDetailsActivity extends BaseActivity {

    ManagerWorkOrderDetailsStates mStates;

    private ManagerDamListAdapter mAdapter;

    /**
     * 工程巡查详情
     */
    WorkOrderDetailBean.DataBean bean;

    WorkOrderDetailBean workOrderDetailBean = new WorkOrderDetailBean();

    @Override
    protected void initViewModel() {

        mStates = getActivityScopeViewModel(ManagerWorkOrderDetailsStates.class);
        accountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new ManagerDamListAdapter(this);
        return new DataBindingConfig(R.layout.activity_nsgf_manager_work_order_dam_details, BR.vm, mStates)
                .addBindingParam(BR.adapter, mAdapter).addBindingParam(BR.click, new ClickProxy());
    }

    private ActivityNsgfManagerWorkOrderDamDetailsBinding mBinding;

    private BottomSheetBehavior<NestedScrollView> mBehavior;

    // 创建Gson对象
    Gson gson = new Gson();
    AccountRequester accountRequester;
    /**
     * 实际巡查路线
     */
    private List<List> actualRoute = new ArrayList<List>();

    private boolean tips;//未巡查部位提示

    @SuppressLint({"InvalidWakeLockTag", "CheckResult"})
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBinding = (ActivityNsgfManagerWorkOrderDamDetailsBinding) getBinding();

        getLifecycle().addObserver(accountRequester);

        bean = getIntent().getParcelableExtra("bean");

        mStates.titleBar.set(getIntent().getStringExtra("title"));


        mBehavior = BottomSheetBehavior.from(mBinding.bottomSheet);
        mBehavior.setState(STATE_COLLAPSED);
        mBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {

                if (newState == STATE_HIDDEN) {
                    mBehavior.setState(STATE_COLLAPSED);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });

        mStates.list.set(bean.getPositionVOS());

        mAdapter.notifyDataSetChanged();

        mAdapter.setOnItemClickListener((viewId, item1, position) ->
                startActivityForResult(new Intent().putExtra("title", item1.getPositionName())
                        .putExtra("item", (Parcelable) item1)
                        .putExtra("position", position)
                        .putExtra("orderCode", bean.getOrderCode())
                        .setClass(this, ManagerWorkOrderFromSubmitActivity.class), 1003));

        accountRequester.getSrc().observe(this, dataResult -> {
            getController().dismissLoading();
            if (dataResult.getResponseStatus().isSuccess()) {
                if (200 == dataResult.getResult().getResponseCode()) {
                    SPUtil.clear(bean.getOrderCode(), this);
                    ToastUtils.showLongToast("提交成功");

                    EventMsg eventMsg = new EventMsg();
                    eventMsg.setMsg("warning");
                    RxBus.get().post(eventMsg);
                    EventBus.getDefault().post(eventMsg);

                } else {

                    if (401 == dataResult.getResult().getResponseCode()) {
                        UserInfo.getInstance().clearUserInfo();
                        finish();
                    }
                    ToastUtils.showLongToast(dataResult.getResult().getMsg());
                }
                finish();
            } else {
                ToastUtils.showLongToast(getErrorMsg(dataResult.getResponseStatus().getE()));
            }
        });

        String url = "file:///android_asset/roadLine/index.html";
        WebSettings mWebSettings = mBinding.webView.getWebView().getSettings();
        mWebSettings.setJavaScriptEnabled(true);//设置支持javaScript
        mBinding.webView.loadUrl(url);
        // 当页面加载完成后调用JavaScript方法
        mBinding.webView.getWebView().setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                //加载初始巡查路线
                if (!StringUtil.isEmpty(bean.getPlanRoute())) {
                    List<List> lists = JSON.parseArray(bean.getPlanRoute(), List.class);
                    JSONArray initArray = new JSONArray();
                    for (int i = 0; i < lists.size(); i++) {

                        String[] doubles = lists.get(i).toString().replace("[", "").replace("]", "").split(",");
                        WorkOrderDetailBean.DataBean.PositionVOSBean positionVOSBean = new WorkOrderDetailBean.DataBean.PositionVOSBean();
                        positionVOSBean.setLat(doubles[1]);
                        positionVOSBean.setLon(doubles[0]);

                        JSONObject initJson = getJsonObject(positionVOSBean);
                        initArray.add(initJson);
                    }
                    //绘制巡查初始路线
                    callJavaScriptDrawInitLineFunction(initArray);
                    //绘制巡查点
                    uploadMaps();
                }

                //加载初始巡查路线
                if (!StringUtil.isEmpty(bean.getActualRoute())) {
                    List<List> lists = JSON.parseArray(bean.getActualRoute(), List.class);
                    actualRoute.addAll(lists);
                    JSONArray initArray = new JSONArray();
                    for (int i = 0; i < lists.size(); i++) {

                        String[] doubles = lists.get(i).toString().replace("[", "").replace("]", "").split(",");
                        WorkOrderDetailBean.DataBean.PositionVOSBean positionVOSBean = new WorkOrderDetailBean.DataBean.PositionVOSBean();
                        positionVOSBean.setLat(doubles[1]);
                        positionVOSBean.setLon(doubles[0]);

                        JSONObject initJson = getJsonObject(positionVOSBean);
                        initArray.add(initJson);
                    }
                    //绘制巡查初始路线
                    callJavaScriptDrawPatrolLineFunction(initArray);
                }
            }
        });


        // 记录第一次巡检时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(Kits.Date.timeStrToSecond(bean.getStartHandleTime()));
        time = Kits.Date.calculateDuration(calendar, Calendar.getInstance());
        mStates.damTime.set("巡查时间:" + (Kits.Date.millisToHMS(time)));
        startTimer();

        String[] permission;


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                permission = new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION,
                        Manifest.permission.POST_NOTIFICATIONS,
                        Manifest.permission.ACCESS_FINE_LOCATION};
            } else {
                if (!isNotificationPermissionGranted()) {
                    showPermissionDialog();
                }
                permission = new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION};
            }
        } else {
            permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
        }

        boolean checkPermissionFirst = PermissionsUtils.checkPermissionFirst(this,1003,permission);

        if (checkPermissionFirst){
            // 绑定到 Service
            Intent intent = new Intent(ManagerWorkOrderDamDetailsActivity.this, LocationService.class);
            // bindService() 用于绑定到 Service
            bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
            // ignoreBatteryOptimization(ManagerWorkOrderDamDetailsActivity.this);
        }else {
            ToastUtils.showLongToast("请允许相关权限，否则无法完成任务");
        }

        /*new RxPermissions(this).request(permission).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) {
                if (aBoolean)
                {

                    // 绑定到 Service
                    Intent intent = new Intent(ManagerWorkOrderDamDetailsActivity.this, LocationService.class);
                    // bindService() 用于绑定到 Service
                    bindService(intent, mServiceConnection, BIND_AUTO_CREATE);

//                    ignoreBatteryOptimization(ManagerWorkOrderDamDetailsActivity.this);

                }
                else {
                    ToastUtils.showLongToast("请允许相关权限，否则无法完成任务");
                }
            }
        });*/

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1003) {
                int position = data.getIntExtra("position", 0);
                //更改巡查点状态 检测是否存在漏检
                for (int i = position; i < mAdapter.getCurrentList().size(); i--) {

                    if (1 != mAdapter.getCurrentList().get(i).getStatus()) {
                        mAdapter.getCurrentList().get(i).setStatus(2);
                        bean.getPositionVOS().get(i).setStatus(2);
                    }
                    if (i == 0) {
                        break;
                    }
                }

                //更改巡查点状态 检测是否存在正在检
                if (position < mAdapter.getCurrentList().size() - 1) {
                    if (0 == mAdapter.getCurrentList().get(position + 1).getStatus()) {
                        mAdapter.getCurrentList().get(position + 1).setStatus(3);
                        bean.getPositionVOS().get(position + 1).setStatus(3);
                    }
                }

                mAdapter.getCurrentList().get(position).setStatus(1);
                bean.getPositionVOS().get(position).setStatus(1);
                // 将Java实体类转换为json字符串
                String json = gson.toJson(bean);
                SPUtil.put(bean.getOrderCode(), json, this);

                mAdapter.notifyDataSetChanged();

                //线进行隐藏 后根据列表进行筛选是否显示
                mBinding.llNsgfManagerDam.setVisibility(View.GONE);
                for (WorkOrderDetailBean.DataBean.PositionVOSBean vosBean : mAdapter.getCurrentList()) {

                    if (vosBean.getStatus() == 2) {
                        if (!tips) {
                            mBinding.llNsgfManagerDam.setVisibility(View.VISIBLE);
                        }
                        break;
                    }
                }


                JSONArray initArray = new JSONArray();
                for (WorkOrderDetailBean.DataBean.PositionVOSBean positionVOSBean : mAdapter.getCurrentList()) {
                    JSONObject initJson = getJsonObject(positionVOSBean);
                    initArray.add(initJson);
                }
                //更新巡查点位状态
                callJavaScriptDrawInitPintFunction(initArray);
            }
        }
    }

    /**
     * 巡查站点
     */
    private void uploadMaps() {

        JSONArray mapBeans = new JSONArray();
        for (WorkOrderDetailBean.DataBean.PositionVOSBean vosBean : bean.getPositionVOS()) {
            JSONObject jsonObject = getJsonObject(vosBean);
            mapBeans.add(jsonObject);
        }
        callJavaScriptDrawInitPintFunction(mapBeans);

    }

    public static class ManagerWorkOrderDetailsStates extends StateHolder {

        public final State<String> name = new State<>(UserInfo.getInstance().getProjectName());
        public final State<String> appLog = new State<>(UserInfo.getInstance().getAppLog());
        public final State<List<WorkOrderDetailBean.DataBean.PositionVOSBean>> list = new State<>(new ArrayList<>());
        public final State<Boolean> loadingVisible = new State<>(false);
        public final State<String> distance = new State<>("");
        public final State<String> damTime = new State<>("巡查时间:");
    }


    /**
     * 巡查提交参数
     */
    private String json = "";

    private Handler handler = new Handler();
    private Runnable runnable;


    long time;

    private void updateTimer() {
        time = time + 1000;
        mStates.damTime.set("巡查时间:" + (Kits.Date.millisToHMS(time)));

    }


    private void startTimer() {
        runnable = new Runnable() {
            @Override
            public void run() {
                updateTimer();
                handler.postDelayed(this, 1000); // 1000毫秒后再次执行
            }
        };
        handler.post(runnable);
    }

    private void stopTimer() {
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        json = SPUtil.get(bean.getOrderCode(), LOCAL_WORK_ORDER_FORM, "", this);

        if (!StringUtil.isEmpty(json)) {
            workOrderDetailBean = gson.fromJson(json, WorkOrderDetailBean.class);
        }
    }

    private boolean isBound = false;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();

        if (myService != null) {
            // 解除绑定服务
            unbindService(mServiceConnection);
            mServiceConnection = null;
            myService.onDestroy();
            myService = null;// 确保不再持有服务的引用
        }

    }

    @Override
    public void onBackPressed() {
        new BaseAlterDialog(this, R.style.dialogstyle,
                getString(R.string.close_work_order_dam),
                getString(R.string.confirm),
                getString(R.string.cancel), (dialog, confirm) -> {

            if (myService != null) {
                // 解除绑定服务
                unbindService(mServiceConnection);
                myService = null;// 确保不再持有服务的引用
            }
            finish();
        }, (dialog, confirm) -> dialog.dismiss()).show();
    }

    public class ClickProxy {

        public void cancel() {

            if (null != workOrderDetailBean) {
                workOrderDetailBean.getData().setActualRoute(actualRoute.toString());
            }
            json = gson.toJson(workOrderDetailBean);

            SPUtil.put(bean.getOrderCode(), LOCAL_WORK_ORDER_FORM, json,
                    ManagerWorkOrderDamDetailsActivity.this);

            SPUtil.put(bean.getOrderCode(), LOCAL_WORK_ORDER_DETAIL, gson.toJson(bean),
                    ManagerWorkOrderDamDetailsActivity.this);

            finish();
        }

        public void close() {
            tips = true;
            mBinding.llNsgfManagerDam.setVisibility(View.GONE);
        }

        public void submit() {

            for (WorkOrderDetailBean.DataBean.PositionVOSBean dataBean : bean.getPositionVOS()) {

                if (1 != dataBean.getStatus()) {
                    ToastUtils.showLongToast("请全部巡查完再提交");
                    return;
                }

            }
            getController().displayLoading();

            if (null != workOrderDetailBean) {
                if (actualRoute.size() == 0) {
                    List<String> list = new ArrayList<>();
                    list.add(String.valueOf(SPUtil.get(SpKey.KEY_USER_INFO, SpKey.KEY_LONGITUDE,
                            "0.0", ManagerWorkOrderDamDetailsActivity.this)));
                    list.add(String.valueOf(SPUtil.get(SpKey.KEY_USER_INFO, SpKey.KEY_LATITUDE,
                            "0.0", ManagerWorkOrderDamDetailsActivity.this)));
                    actualRoute.add(list);
                }
                workOrderDetailBean.getData().setActualRoute(actualRoute.toString());
            }
            workOrderDetailBean.getData().setOrderCode(bean.getOrderCode());
            json = gson.toJson(workOrderDetailBean.getData());
            accountRequester.handleWorkOrder(JSON.parseObject(json));

        }
    }

    /**
     * 绘制巡查路线
     *
     * @param list
     */
    private void callJavaScriptDrawPatrolLineFunction(JSONArray list) {
        Log.e("绘制巡查路线============", list.toString());
        mBinding.webView.getWebView().evaluateJavascript("drawPatrolLine(" + list + "," + true + ");",
                null);
    }

    /**
     * 绘制巡查初始路线
     *
     * @param list
     */
    private void callJavaScriptDrawInitLineFunction(JSONArray list) {
        Log.e("绘制巡查初始路线============", list.toString());
        mBinding.webView.getWebView().evaluateJavascript("drawInitLine(" + "'" + list + "'" + ");",
                null);
    }

    /**
     * 绘制巡查点位
     *
     * @param list
     */
    private void callJavaScriptDrawInitPintFunction(JSONArray list) {
        mBinding.webView.getWebView().evaluateJavascript("drawInitPint(" + "'" + list + "'" + ");",
                null);
    }

    /**
     * @return
     */
    private void patrolLine() {

        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < actualRoute.size(); i++) {
            String[] doubles = actualRoute.get(i).toString()
                    .replace("[", "")
                    .replace("]", "").split(",");
            WorkOrderDetailBean.DataBean.PositionVOSBean positionVOSBean = new WorkOrderDetailBean.DataBean.PositionVOSBean();
            positionVOSBean.setLat(doubles[1]);
            positionVOSBean.setLon(doubles[0]);
            JSONObject initJson = getJsonObject(positionVOSBean);
            jsonArray.add(initJson);
        }

        //绘制巡查初始路线
        callJavaScriptDrawPatrolLineFunction(jsonArray);
        calculateDistance(jsonArray);
    }

    /**
     * 计算巡查总里程
     */
    private void calculateDistance(JSONArray list) {
        double distance = 0.0;

        for (int i = 1; i < list.size(); i++) {
            distance = distance
                    + Utils.calculateDistance(Double.parseDouble(((JSONObject) list.get(i)).getString("lat").toString()),
                    Double.parseDouble(((JSONObject) list.get(i)).getString("lon").toString()),
                    Double.parseDouble(((JSONObject) list.get(i - 1)).getString("lat").toString()),
                    Double.parseDouble(((JSONObject) list.get(i - 1)).getString("lon").toString()));
        }

        mStates.distance.set("里程:" + df.format(distance / 1000) + "km");

    }

    //保留两位小数
    private DecimalFormat df = new DecimalFormat("#####0.00");

    LocationService locationService;

    /**
     * 忽略电池优化
     */
    private void ignoreBatteryOptimization(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);

            boolean hasIgnored = powerManager.isIgnoringBatteryOptimizations(activity.getPackageName());
            //  判断当前APP是否有加入电池优化的白名单，如果没有，弹出加入电池优化的白名单的设置对话框。
            if (!hasIgnored) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.notifyTitle);
                builder.setMessage("为了方便您及时收到通知消息、会议通知建议您选择无限制");

                // 拒绝, 退出应用
                builder.setNegativeButton(R.string.cancel,
                        (dialog, which) -> dialog.dismiss());

                builder.setPositiveButton(R.string.setting,
                        (dialog, which) -> {

                            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                            intent.setData(Uri.parse("package:" + activity.getPackageName()));
                            if (intent.resolveActivity(getPackageManager()) != null) {
                                startActivity(intent);
                            }
                        });

                builder.setCancelable(false);

                builder.show();

            } else {

                // 绑定到 Service
                Intent intent = new Intent(this, LocationService.class);
                // bindService() 用于绑定到 Service
                bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
            }
        }
    }

    LocationService myService;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            Log.e("巡查定位：", "绑定回调");
            LocationService.Binder binder = (LocationService.Binder) iBinder;
            myService = binder.getService();
            // 绑定成功回调
            isBound = true;
            myService.setCallback(new LocationService.Callback() {
                @Override
                public void onDataChange(Location location) {

                    // 当位置更新时，这里处理位置信息
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();

                    List<String> list = new ArrayList<>();
                    list.add(String.valueOf(longitude));
                    list.add(String.valueOf(latitude));
                    actualRoute.add(list);

                    if (null != workOrderDetailBean) {
                        workOrderDetailBean.getData().setActualRoute(actualRoute.toString());
                    }
                    bean.setActualRoute(actualRoute.toString());
                    patrolLine();

                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false;
            myService = null;
            Log.e("巡查定位：", "解绑回调");
        }
    };

}
